<?php

class CheckoutController extends Controller
{
    public $breadcrumb = "";
	public $key = 'fucking code';
	
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
    public function actionCart()
    {
		$list_mail = array('lekimthuy@boxanhfoods.vn','lequoccuong@boxanhfoods.vn','ngongocgiang@boxanhfoods.vn','nguyenkyquang@boxanhfoods.vn');
        $products       = array();
        $total          = 0;
		$model = new OrderFrontEnd;
		if(isset($_POST['ListDel']) && isset(Yii::app()->session[SITE_ID . '_cart']) && !empty(Yii::app()->session[SITE_ID . '_cart']))
		{
			foreach($_POST['ListDel'] as $del ){
				$cartIds = Yii::app()->session[SITE_ID . '_cart'];
				unset($cartIds[$del]);
				Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
			}
		}
		if(isset($_POST['OrderFrontEnd']) && isset(Yii::app()->session[SITE_ID . '_cart']) && !empty(Yii::app()->session[SITE_ID . '_cart']))
		{
			$tmp = $_POST['OrderFrontEnd'];
			$tmp['order_id'] = createRandomString();
			$tmp['status'] = 0;
			$tmp['creation_datetime'] = date('Y-m-d H:i:s', time());
			$model->attributes=$tmp;
			if($model->validate()){
			
				if($model->save()){
					
					$order = OrderFrontEnd::model()->findAll('order_id=\''.$tmp['order_id'].'\'');
					$productsInCart = Yii::app()->session[SITE_ID . '_cart'];
					$cartIds		= $productsInCart;
					$tr = '';
					$i = 1;
					$sl = 0;
					$thanh_tien = 0;
					foreach ($productsInCart as $id => $qty) {
						$product = Product::model()->findByPk($id);
						if (is_object($product)) {
							$price = $product->on_sale;
							$total = $product->on_sale*$qty;
							$OrderDetail = new OrderDetail;
							$order_tmp['order_id'] = $order[0]->id;
							$order_tmp['product_id'] = $id;
							$order_tmp['quantity'] = $qty;
							$order_tmp['price'] = $product->on_sale;
							$order_tmp['total'] = $total;
							$sl += $qty;
							$thanh_tien += $total;
							$OrderDetail->attributes = $order_tmp;
							if ($qty > 0 ){
								if( $OrderDetail->save() ){
									$tr .= "<tr>
												<td style='border:1px solid black;'>".$i++."</td>
												<td style='border:1px solid black;'>".$product->name."</td>
												<td style='border:1px solid black;'>".number_format($product->on_sale,0)."</td>
												<td style='border:1px solid black;'>".$qty."</td>
												<td style='border:1px solid black;'>".number_format($total,0)."</td>
											</tr>";
									unset($cartIds[$id]);
									Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
								}
							}
							else{
								unset($cartIds[$id]);
								Yii::app()->session[SITE_ID . '_cart'] = $cartIds;
							}
						}
						
					}
					// if ( empty($cartIds)){
							$str = "Chào bạn,<br><br>Chúng tôi đã nhận được đơn đặt hàng của bạn bao gồm:<br><br>";
							$str .= "<table style='border-collapse:collapse;'><tr style='border:1px solid black;'><td style='border:1px solid black;'>STT</td><td style='border:1px solid black;'>Sản phẩm</td><td style='border:1px solid black;'>Giá đơn vị</td><td style='border:1px solid black;'>Số lượng</td><td style='border:1px solid black;'>Thành tiền</td></tr>";
							$str .= $tr;
							$str .= "<tr style='border:1px solid black;'>
								<td colspan='3'style='border:1px solid black;'>Tổng cộng:</td>
								<td style='border:1px solid black;'>".number_format($sl,0)."</td>
								<td style='border:1px solid black;'>".number_format($thanh_tien,0)." VNĐ</td>
							</tr>";							$mail1 = Yii::createComponent('application.extensions.mailer.EMailer');
							$mail1->Host = 'mail.boxanhfoods.vn';
							$mail1->IsSMTP();
							$mail1->IsHTML(true);
							$mail1->CharSet = 'UTF-8';
							$mail1->SMTPAuth=true;
							$mail1->From = 'sales@boxanhfoods.vn';
							$mail1->Port = 25;
							$mail1->Username = 'sales@boxanhfoods.vn';
							$mail1->Password = 'U8f5os%Gy~Xs';
							$mail1->FromName = 'Sales Bo xanh foods';
							$mail1->AddReplyTo('sales@boxanhfoods.vn');
							$mail1->AddAddress($tmp['email']);
							$mail1->Subject = 'Bo xanh foods gửi bạn kết quả giao dịch số #'.$tmp['order_id'];
							$mail1->Body =  $str.'<br><br> Trân trọng,<br>Cám ơn.';
							$mail1->Send();														
							sleep(2);
							
							$mail2 = Yii::createComponent('application.extensions.mailer.EMailer');							
							$mail2->Host = 'mail.boxanhfoods.vn';							
							$mail2->IsSMTP();							
							$mail2->IsHTML(true);							
							$mail2->CharSet = 'UTF-8';							
							$mail2->SMTPAuth=true;							
							$mail2->From = 'notification@boxanhfoods.vn';							
							$mail2->Port = 25;							
							$mail2->Username = 'notification@boxanhfoods.vn';							
							$mail2->Password = 'R#[rl=#0$q0M';							
							$mail2->FromName = 'Sales Bo xanh foods';							
							$mail2->AddReplyTo('notification@boxanhfoods.vn');		
							foreach($list_mail as $value)
								$mail2->AddAddress($value);							
							$mail2->Subject = 'Bo xanh foods gửi bạn kết quả giao dịch số #'.$tmp['order_id'];							
							$mail2->Body =  $str.'<br><br> Xem chi tiết giao dịch tại: <a href="http://boxanhfoods.vn/'.$this->createUrl('admin/orderAdmin/view',array('id' => $order[0]->id)).'" >http://boxanhfoods.vn/'.$this->createUrl('admin/orderAdmin/view',array('id' => $order[0]->id)).'</a> <br><br> Trân trọng,<br>Cám ơn.';							
							$mail2->Send();
					// }
					$time_order_created = time();
					$this->redirect($this->createUrl('checkout/checkoutSuccess',array('order_id' => $tmp['order_id'],'time' => $time_order_created,'email' => $tmp['email'],'token' => md5($tmp['order_id'].$time_order_created.$tmp['email'].$this->key))));
				}
			}
		}
        if (isset(Yii::app()->session[SITE_ID . '_cart']) && !empty(Yii::app()->session[SITE_ID . '_cart'])) {
            $productsInCart = Yii::app()->session[SITE_ID . '_cart'];
            foreach ($productsInCart as $id => $qty) {
                $product = Product::model()->findByPk($id);
                if (is_object($product)) {
                    $products[$id]['product'] = $product;
                    $products[$id]['qty']     = $qty;
                    $total += $product->on_sale * $qty;
                }
            }
        }

        $this->breadcrumb = "Cart";
        $this->layout     = "CheckoutLayout";
        $this->render(
            "cart",
            array(
                'products' => $products,
                'total'    => $total,
				'model'    => $model,
            )
        );
    }
	public function actionCheckoutSuccess($order_id='',$time='',$email = '', $token='')
    {
		if($order_id && $time && $email && $token){
			$products       = array();
			$total          = 0;
			$info['order_id'] = $order_id;
			$info['time'] = $time;
			$info['token'] = $token;
			$info['email'] = $email;
			
			$this->breadcrumb = "Cart";
			$this->layout     = "CheckoutLayout";
			$this->render(
				"checkout-success",
				array(
					'products' => $products,
					'total'    => $total,
					'info'		=> $info,
				)
			);
		}
		else{
			$products       = array();
			$total          = 0;
			$info['order_id'] = 0;
			$info['time'] = 0;
			$info['token'] = 0;
			$info['email'] = '';
			
			$this->breadcrumb = "Cart";
			$this->layout     = "CheckoutLayout";
			$this->render(
				"checkout-success",
				array(
					'products' => $products,
					'total'    => $total,
					'info'		=> $info,
				)
			);
		}
    }
}
function createRandomString($string_length=9, $character_set='23456789ABCDEFGHJKLMNPQRSTUVWXYZ') {
        $random_string = array();
        for ($i = 1; $i <= $string_length; $i++) {
            $rand_character = $character_set[rand(0, strlen($character_set) - 1)];
            $random_string[] = $rand_character;
        }
        shuffle($random_string);
        return implode('', $random_string);
}